trigger Cald_CalculateAttainmentForClaims on Callidus_Claim__c (after update) 
{
    Map<Id, Id> participantsMap = new Map<Id, Id>();
    Map<Id, Id> plansMap = new Map<Id, Id>();
    Map<Id, Double> participantsApprovedMap = new Map<Id, Double>();
    List<Callidus_Plan_Participant__c> ppList = new List<Callidus_Plan_Participant__c>();
    List<Callidus_Plan_Participant__c> updatePpList = new List<Callidus_Plan_Participant__c>();
    List<Callidus_Claim__c> claimCommissionsChangedList = new List<Callidus_Claim__c>();
    List<Callidus_Claim_Detail__c> claimDetailsList = new List<Callidus_Claim_Detail__c>();
    Map<Integer, String> getMonth = new Map<Integer, String>();
    getMonth.put(1, 'Jan');
    getMonth.put(2, 'Feb');
    getMonth.put(3, 'Mar');
    getMonth.put(4, 'Apr');
    getMonth.put(5, 'May');
    getMonth.put(6, 'Jun');
    getMonth.put(7, 'Jul');
    getMonth.put(8, 'Aug');
    getMonth.put(9, 'Sep');
    getMonth.put(10, 'Oct');
    getMonth.put(11, 'Nov');
    getMonth.put(12, 'Dec');
    
    Map<String, String> getAdjacentPeriod = new Map<String, String>();
    List<String> periodList = new List<String>();
    Map<Id, Id> planUsersMap = new Map<Id, Id>();
    Map<Id, Id> standaloneUsersMap = new Map<Id, Id>();
    List<ID> participantsList = new List<ID>();
    
    Callidus_Plan_Participant__c pp = null;
    Integer yearNo = 0;
    String currentPeriod = '';
    Date oppCloseDate = null;
    Callidus_Plan_Participant__c[] planParticipantsList = new Callidus_Plan_Participant__c[]{};
    
    try
    {
        Callidus_Claim__c[] approvedClaimsList = [select id, Attainment__c, Credit__c, Adjusted_Credit__c, Adjusted_Commission__c, Commission_Amount__c, Commission_Rate__c, Participant__c, Plan__c, Claim_Status__c, Temporary_Status__c, Opportunity__r.CloseDate, (select Requested_Credit__c, Requested_Commission__c, Requested_Rate__c, Split__c, Claim__c, Claimant__c, Approved_Credit__c, Approved_Commission__c, Payout_Type__c, Plan__c from Claim_Details__r) from Callidus_Claim__c where id in :Trigger.new and Claim_Status__c = 'Approved' and Temporary_Status__c = null];
        Callidus_Claim_Status_Credit__c[] existingCSCList = null;
        for(Callidus_Claim__c c : approvedClaimsList)
        {
            oppCloseDate = c.Opportunity__r.CloseDate;
            if(c.Claim_Status__c == 'Approved' && c.Temporary_Status__c == null)
            {
                system.debug('First -----   '+c);
                yearNo = c.Opportunity__r.CloseDate.year();//get the year of the Opportunity
                currentPeriod = getMonth.get(c.Opportunity__r.CloseDate.month())+'-'+yearNo;
                participantsMap.put(c.Participant__c, c.Participant__c);
                
                claimDetailsList = c.Claim_Details__r;
                
                for(Callidus_Claim_Detail__c ccd : c.Claim_Details__r)
                {
                    participantsMap.put(ccd.Claimant__c, ccd.Claimant__c);
                    plansMap.put(ccd.Plan__c, ccd.Plan__c);
                }
                if(c.Plan__c != null)
                    plansMap.put(c.Plan__c, c.Plan__c);

	            c.Temporary_Status__c = 'Approved';
	            claimCommissionsChangedList.add(c);
            }

            
            existingCSCList = [select id, Participant__c, Amount__c, Commission__c, FYear__c, Claim_Status__c from Callidus_Claim_Status_Credit__c where Participant__c in :participantsMap.keySet() and FYear__c = :yearNo];            
            for(Callidus_Claim_Status_Credit__c csc :existingCSCList)
            {
                if(c.Claim_Details__r.size() == 0)
                {
                    if(csc.Participant__c == c.Participant__c && csc.Claim_Status__c == 'Pending Claims')
                    {
                        csc.Amount__c -= c.Credit__c;
                        csc.Commission__c -= c.Commission_Amount__c;
                    }
                    else if(csc.Participant__c == c.Participant__c && csc.Claim_Status__c == 'Approved Claims')
                    {
                        csc.Amount__c += c.Adjusted_Credit__c;
                        csc.Commission__c += c.Adjusted_Commission__c;
                    }
                }
                for(Callidus_Claim_Detail__c ccd : c.Claim_Details__r)
                {
                    if(csc.Participant__c == ccd.Claimant__c && csc.Claim_Status__c == 'Pending Claims')
                    {
                        csc.Amount__c -= ccd.Requested_Credit__c;
                        csc.Commission__c -= ccd.Requested_Commission__c;
                    }
                    else if(csc.Participant__c == ccd.Claimant__c && csc.Claim_Status__c == 'Approved Claims')
                    {
                        csc.Amount__c += ccd.Approved_Credit__c;
                        csc.Commission__c += ccd.Approved_Commission__c;
                    }
                }
            }    
            system.debug('Existing CSCList ---------------  '+existingCSCList);
    
            getAdjacentPeriod.put('Jan-'+yearNo, '');
            getAdjacentPeriod.put('Feb-'+yearNo, 'Jan-'+yearNo);
            getAdjacentPeriod.put('Mar-'+yearNo, 'Feb-'+yearNo);
            getAdjacentPeriod.put('Apr-'+yearNo, '');
            getAdjacentPeriod.put('May-'+yearNo, 'Apr-'+yearNo);
            getAdjacentPeriod.put('Jun-'+yearNo, 'May-'+yearNo);
            getAdjacentPeriod.put('Jul-'+yearNo, '');
            getAdjacentPeriod.put('Aug-'+yearNo, 'Jul-'+yearNo);
            getAdjacentPeriod.put('Sep-'+yearNo, 'Aug-'+yearNo);
            getAdjacentPeriod.put('Oct-'+yearNo, '');
            getAdjacentPeriod.put('Nov-'+yearNo, 'Oct-'+yearNo);
            getAdjacentPeriod.put('Dec-'+yearNo, 'Nov-'+yearNo);
    
            periodList.add('Jan-'+yearNo);
            periodList.add('Feb-'+yearNo);
            periodList.add('Mar-'+yearNo);
            periodList.add('Apr-'+yearNo);
            periodList.add('May-'+yearNo);
            periodList.add('Jun-'+yearNo);
            periodList.add('Jul-'+yearNo);
            periodList.add('Aug-'+yearNo);
            periodList.add('Sep-'+yearNo);
            periodList.add('Oct-'+yearNo);
            periodList.add('Nov-'+yearNo);
            periodList.add('Dec-'+yearNo);
        }

        List<Callidus_Claim_Detail__c> creditClaimsDetailList = [select Requested_Credit__c, Requested_Commission__c, Requested_Rate__c, Claim__c, Claimant__c, Approved_Credit__c, Approved_Commission__c, Plan__c, Payout_Type__c from Callidus_Claim_Detail__c  c where c.Plan__c in :plansMap.keySet() and c.Claimant__c in :participantsMap.keyset() and c.Claim__r.Claim_Status__c = 'Approved'];

    	for(Callidus_Claim_Detail__c ccd: claimDetailsList)
    	{    
	        if(ccd.Plan__c != null)
	        {
	            planParticipantsList = [select id, Period__c, PTD_Attainment__c, QTD_Attainment__c, YTD_Attainment__c, PTD_Commission__c, QTD_Commission__c, YTD_Commission__c, PTD_Credit__c, QTD_Credit__c, YTD_Credit__c, Close_Date__c  from Callidus_Plan_Participant__c where Plan__c = :ccd.Plan__c and Participant__c = :ccd.Claimant__c and FYear__c = :yearNo order by createddate];
	            
	            Callidus_Plan__c[] plansList = [select id, Quota__c, OTE__c, (SELECT Participant__c, Quota__c FROM Plan_Assignable__r), (select Min_Attainment__c, Max_Attainment__c, Min_Credit__c, Max_Credit__c, Rate_Type__c, Rate__c from Rates__r) from Callidus_Plan__c where id = :ccd.Plan__c];
	            Double Quota = 0;
	            for(Integer j=0; j<plansList[0].Plan_Assignable__r.size(); j++)
	            {
	                if(plansList[0].Plan_Assignable__r[j].Participant__c == ccd.Claimant__c)
	                {
	                    Quota = plansList[0].Plan_Assignable__r[j].Quota__c;
	                    break;
	                }
	            }
	            //Double OTE = plansList[0].OTE__c;
	        
	            for(Callidus_Claim_Status_Credit__c csc :existingCSCList)
	            {
	                if(csc.Participant__c == ccd.Claimant__c && csc.Claim_Status__c == 'Pending Claims')
	                    csc.Attainment__c = (csc.Amount__c.doubleValue() * 100) / Quota;
	                else if(csc.Participant__c == ccd.Claimant__c && csc.Claim_Status__c == 'Approved Claims')
	                    csc.Attainment__c = (csc.Amount__c.doubleValue() * 100) / Quota;
	                system.debug('entereddddddddddddddddd   CSC    '+csc);
	            }    
	            
	            Callidus_Rate__c[] ratesList = plansList[0].Rates__r;
	            
	            String rateType = ratesList[0].Rate_Type__c;
	            system.debug('RateType   -------------------------- '+rateType);
	            Double approvedClaimedCredit = 0;
	            Double approvedClaimedCommission = 0;
	            
	            Boolean obtainOTE = false;
	            for(Callidus_Claim_Detail__c c: creditClaimsDetailList)
	            {
	                system.debug(creditClaimsDetailList.size()+'  ---  Approved CLaimed Credit 1: '+approvedClaimedCredit);
	                system.debug('Approved CLaimed Commission   1: '+approvedClaimedCommission);
                    if(c.Claimant__c == ccd.Claimant__c)
                    {
                        approvedClaimedCredit += c.Approved_Credit__c;
		                approvedClaimedCommission += c.Approved_Commission__c;
                    }
	            }
	            system.debug('Approved CLaimed Credit : '+approvedClaimedCredit);
	            system.debug('Approved CLaimed Commission   : '+approvedClaimedCommission);
	
	            List<Double> ratePercentList = new List<Double>();
	            if(rateType == 'Attainment')
	            {
	                Double attPercent = (approvedClaimedCredit  * 100)/ Quota;
	    
	                for(Callidus_Rate__c r : ratesList)
	                {
	                    if(attPercent >= r.Min_Attainment__c && attPercent <= r.Max_Attainment__c)
	                    {
	                        ratePercentList.add(r.Rate__c);
	                        break;
	                    }
	                }   
	
	                //for(Callidus_Claim__c c: approvedClaimsList)
	                //{
	                    //c.Attainment__c = attPercent;
	                    //approvedClaimedCommission -= c.Adjusted_Commission__c;
	                    //c.Adjusted_Commission__c = (c.Adjusted_Credit__c * ratePercentList[0])/100;
	                    //approvedClaimedCommission += c.Adjusted_Commission__c;
	                    //c.Commission_Rate__c = ratePercentList[0];
	                    
	                   // c.Temporary_Status__c = 'Approved';
	                   // claimCommissionsChangedList.add(c);
	                    
                   if(planParticipantsList.size() == 0)
                    {
                        pp = new Callidus_Plan_Participant__c(Participant__c = ccd.Claimant__c, OwnerId = ccd.Claimant__c, Plan__c = ccd.Plan__c, YTD_Attainment__c = attPercent, YTD_Credit__c = ccd.Approved_Credit__c, PTD_Credit__c = ccd.Approved_Credit__c, QTD_Credit__c = ccd.Approved_Credit__c, YTD_Commission__c = ccd.Approved_Commission__c,  QTD_Commission__c = ccd.Approved_Commission__c, PTD_Commission__c = ccd.Approved_Commission__c, FYear__c = yearNo, period__c = currentPeriod, Close_Date__c = oppCloseDate.toStartOfMonth());
                        system.debug('Plan Participant is ======= '+pp);
                        ppList.add(pp);
                    }
                    else
                    {
                        Boolean currentPeriodExists = false;
                        Callidus_Plan_Participant__c existPlanParticipant = null;
                        Callidus_Plan_Participant__c adjacentPlanParticipant = null;
                        for(Integer i=0; i<planParticipantsList.size(); i++)
                        {
                            if(planParticipantsList[i].Period__c == currentPeriod)
                            {
                                existPlanParticipant = planParticipantsList[i];
                                break;
                            }
                        }//end of for(Integer i=0;)

                        if(existPlanParticipant == null)// a new entry with the current period in Plan Participant object
                        {
                            pp = new Callidus_Plan_Participant__c(Participant__c = ccd.Claimant__c, OwnerId = ccd.Claimant__c, Plan__c = ccd.Plan__c, YTD_Attainment__c = attPercent, YTD_Credit__c = approvedClaimedCredit, PTD_Credit__c = ccd.Approved_Credit__c, QTD_Credit__c =  ccd.Approved_Credit__c, YTD_Commission__c = approvedClaimedCommission,  QTD_Commission__c = ccd.Approved_Commission__c, PTD_Commission__c = ccd.Approved_Commission__c, FYear__c = yearNo, period__c = currentPeriod, Close_Date__c = oppCloseDate.toStartOfMonth());
                            system.debug('Plan Participant 222222  is ======= '+pp);
                            ppList.add(pp);
                            
                        }                       
                        else
                        {
                            existPlanParticipant.YTD_Attainment__c = attPercent;
                            existPlanParticipant.YTD_Credit__c = approvedClaimedCredit;
                            existPlanParticipant.PTD_Credit__c += ccd.Approved_Credit__c;
                            existPlanParticipant.QTD_Credit__c += ccd.Approved_Credit__c;
                            existPlanParticipant.YTD_Commission__c = approvedClaimedCommission;
                            existPlanParticipant.QTD_Commission__c += ccd.Approved_Commission__c;
                            existPlanParticipant.PTD_Commission__c += ccd.Approved_Commission__c; 
                            
                            system.debug('Plan Participant 3333333333333  is ======= '+existPlanParticipant);
                            updatePpList.add(existPlanParticipant);
                                                
                        }
                    }
	                    
	               // }
	            }//end of (rateType == 'Attainment')
	            else//if rateType is Credit
	            {
	                for(Callidus_Rate__c r : ratesList)
	                {
	                    if(approvedClaimedCredit >= r.Min_Credit__c && approvedClaimedCredit <= r.Max_Credit__c)
	                    {
	                        ratePercentList.add(r.Rate__c);
	                        break;
	                    }
	                }   
	                
	                for(Callidus_Claim__c c: approvedClaimsList)
	                {
/*	                    c.Attainment__c = approvedClaimedCredit;
	                    approvedClaimedCommission -= c.Adjusted_Commission__c;
	                    c.Adjusted_Commission__c = (c.Adjusted_Credit__c * ratePercentList[0])/100;
	                    approvedClaimedCommission += c.Adjusted_Commission__c;
	                    c.Commission_Rate__c = ratePercentList[0];
	                    c.Temporary_Status__c = 'Approved';
	                    claimCommissionsChangedList.add(c);
	*/                    
	                    if(planParticipantsList.size() == 0)
	                    {
	                        pp = new Callidus_Plan_Participant__c(Participant__c = ccd.Claimant__c, OwnerId = ccd.Claimant__c, Plan__c = ccd.Plan__c, YTD_Credit__c = ccd.Approved_Credit__c, PTD_Credit__c = ccd.Approved_Credit__c, QTD_Credit__c =  ccd.Approved_Credit__c, YTD_Commission__c =  ccd.Approved_Commission__c,  QTD_Commission__c = ccd.Approved_Commission__c, PTD_Commission__c = ccd.Approved_Commission__c, FYear__c = yearNo, period__c = currentPeriod, Close_Date__c = oppCloseDate.toStartOfMonth());
	                        ppList.add(pp);
	                    }
	                    else
	                    {
	                        Boolean currentPeriodExists = false;
	                        Callidus_Plan_Participant__c existPlanParticipant = null;
	                        Callidus_Plan_Participant__c adjacentPlanParticipant = null;
	                        for(Integer i=0; i<planParticipantsList.size(); i++)
	                        {
	                            if(planParticipantsList[i].Period__c == currentPeriod)
	                            {
	                                existPlanParticipant = planParticipantsList[i];
	                                break;
	                            }
	                        }//end of for(Integer i=0;)
	
	                        if(existPlanParticipant == null)// a new entry with the current period in Plan Participant object
	                        {
	                            pp = new Callidus_Plan_Participant__c(Participant__c = ccd.Claimant__c, OwnerId = ccd.Claimant__c, Plan__c = ccd.Plan__c, YTD_Credit__c = approvedClaimedCredit, PTD_Credit__c = ccd.Approved_Credit__c, QTD_Credit__c = ccd.Approved_Credit__c, YTD_Commission__c = approvedClaimedCommission,  QTD_Commission__c = ccd.Approved_Commission__c, PTD_Commission__c = ccd.Approved_Commission__c, FYear__c = yearNo, period__c = currentPeriod, Close_Date__c = oppCloseDate.toStartOfMonth());
	                            ppList.add(pp);
	                            
	                        }                       
	                        else
	                        {
	                            existPlanParticipant.YTD_Credit__c = approvedClaimedCredit;
	                            existPlanParticipant.PTD_Credit__c += ccd.Approved_Credit__c;
	                            existPlanParticipant.QTD_Credit__c += ccd.Approved_Credit__c;
	                            existPlanParticipant.YTD_Commission__c = approvedClaimedCommission;
	                            existPlanParticipant.QTD_Commission__c += ccd.Approved_Commission__c;
	                            existPlanParticipant.PTD_Commission__c += ccd.Approved_Commission__c; 
	                            
	                            updatePpList.add(existPlanParticipant);
	                                                
	                        }
	                    }
	                    
	                    
	                }
	            }//end of else
	        }//end of if
	        else//if Claim is Standalone
	        {
	            planParticipantsList = [select id, Period__c, PTD_Attainment__c, QTD_Attainment__c, YTD_Attainment__c, PTD_Commission__c, QTD_Commission__c, YTD_Commission__c, PTD_Credit__c, QTD_Credit__c, YTD_Credit__c, Close_Date__c  from Callidus_Plan_Participant__c where Participant__c = : ccd.Claimant__c and FYear__c = :yearNo order by createddate];
	            Decimal Max_YTDCredit = 0;
	            Decimal Max_YTDCommission = 0;
	            
	            for(Callidus_Claim__c c: approvedClaimsList)
	            {
	                
	                if(planParticipantsList.size() == 0)
	                {
	                    pp = new Callidus_Plan_Participant__c(Participant__c = ccd.Claimant__c, OwnerId = ccd.Claimant__c,YTD_Credit__c = ccd.Approved_Credit__c, PTD_Credit__c = ccd.Approved_Credit__c, QTD_Credit__c = ccd.Approved_Credit__c, YTD_Commission__c = ccd.Approved_Commission__c,  QTD_Commission__c = ccd.Approved_Commission__c, PTD_Commission__c = ccd.Approved_Commission__c, FYear__c = yearNo, period__c = currentPeriod, Close_Date__c = oppCloseDate.toStartOfMonth());
	                    ppList.add(pp);
	                }
	                else
	                {
	                    Boolean currentPeriodExists = false;
	                    Callidus_Plan_Participant__c existPlanParticipant = null;
	                    Callidus_Plan_Participant__c adjacentPlanParticipant = null;
	                    for(Integer i=0; i<planParticipantsList.size(); i++)
	                    {
	                        if(planParticipantsList[i].Period__c == currentPeriod)
	                        {
	                            existPlanParticipant = planParticipantsList[i];
	                            break;
	                        }
	                    }//end of for(Integer i=0;)
	
	                    for(Integer i=0; i<planParticipantsList.size(); i++)
	                    {
	                        if(Max_YTDCredit < planParticipantsList[i].YTD_Credit__c)
	                            Max_YTDCredit = planParticipantsList[i].YTD_Credit__c;
	                        if(Max_YTDCommission < planParticipantsList[i].YTD_Commission__c)
	                            Max_YTDCommission = planParticipantsList[i].YTD_Commission__c;
	                    }//end of for(Integer i=0;)
	
	                    if(existPlanParticipant == null)// a new entry with the current period in Plan Participant object
	                    {
	                        pp = new Callidus_Plan_Participant__c(Participant__c = ccd.Claimant__c, OwnerId = ccd.Claimant__c,YTD_Credit__c = (Max_YTDCredit + ccd.Approved_Credit__c), PTD_Credit__c =  ccd.Approved_Credit__c, QTD_Credit__c =  ccd.Approved_Credit__c, YTD_Commission__c = (Max_YTDCommission +  ccd.Approved_Commission__c),  QTD_Commission__c =  ccd.Approved_Commission__c, PTD_Commission__c =  ccd.Approved_Commission__c, FYear__c = yearNo, period__c = currentPeriod, Close_Date__c = oppCloseDate.toStartOfMonth());
	                        ppList.add(pp);
	                        
	                    }                       
	                    else
	                    {
	                        existPlanParticipant.YTD_Credit__c = Max_YTDCredit +  ccd.Approved_Credit__c;
	                        existPlanParticipant.PTD_Credit__c +=  ccd.Approved_Credit__c;
	                        existPlanParticipant.QTD_Credit__c +=  ccd.Approved_Credit__c;
	                        existPlanParticipant.YTD_Commission__c = Max_YTDCommission +  ccd.Approved_Commission__c;
	                        existPlanParticipant.QTD_Commission__c +=  ccd.Approved_Commission__c;
	                        existPlanParticipant.PTD_Commission__c +=  ccd.Approved_Commission__c; 
	                        
	                        updatePpList.add(existPlanParticipant);
	                                            
	                    }
	                }
/*	                c.Attainment__c = Max_YTDCredit +  ccd.Approved_Credit__c;
	                c.Temporary_Status__c = 'Approved';
	                claimCommissionsChangedList.add(c);*/
	                
	            }
	        } 
    	}

        update existingCSCList;

        if(ppList.size() > 0)
            insert ppList;
            
        if(updatePpList.size() > 0)
            update updatePpList;
            
        if(claimCommissionsChangedList.size() > 0)
            update claimCommissionsChangedList;
    }
    catch(Exception e)
    {
    }

}